from pymongo import Connection

def request(request, func, db, table, enabled = True, name = 'index'):
    if enabled:
        attrs = []
        for key, val in request.items():
            key, val = key.lower(), val.lower()
            val = val.split('|') if '|' in val else [val]
            for v in val: attrs.append({key: v})
        
        # Connect to the cache server
        cn = Connection()
        tb = cn[db][table]

        # Find the set of all matching objects
        items = []
        for attr in attrs:
            cache = tb.find(dict(('%s.%s' % (name, key), val) for key,val in attr.items()))
            if cache.count() != 0:
                # A set of items in the cache was found
                for item in cache: items.append(item)
            else:
                # Nothing found in the cache, make a request
                search = func(dict(request, **attr))
                for item in search:
                    item[name] = attr 
                    items.append(item)
                tb.insert(search)

        # Format the items and return
        for item in items: item['_id'] = str(item['_id'])
        return items
    else:
        # Do not use the cache to request items
        return func(request)
